package cn.zj.logistics.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import cn.zj.logistics.pojo.User;

public class MyFormAuthenticationFilter extends FormAuthenticationFilter {

	
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		//从请求中获取Shiro的 主体
		Subject subject = getSubject(request, response);
		//从主体中获取Shiro框架的Session
		Session session = subject.getSession();
		//如果主体没有认证（Session中认证）并且 主体已经设置记住我了
		if (!subject.isAuthenticated() && subject.isRemembered()) {
			//获取主体的身份（从记住我的Cookie中获取的）
			User principal = (User) subject.getPrincipal();
			//将身份认证信息共享到 Session中
			session.setAttribute("USER_IN_SESSION", principal);
		}
		return subject.isAuthenticated() || subject.isRemembered();
	}
	
	
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		HttpServletRequest req = (HttpServletRequest) request;

		// 1，先从request请求对象中获取 用户提交表单参数 验证码
		String verifyCode = req.getParameter("verifyCode");
		String username = req.getParameter("verifyCode");
		System.out.println("username :"+username);
		System.out.println("verifyCode :" + verifyCode);
		// 2，从Session获取共享的 随机码
		String randCode = (String) req.getSession().getAttribute("rand");
		if (StringUtils.isNotBlank(verifyCode) && StringUtils.isNotBlank(randCode)) {
			// 将用户提交的验证码和Session中的随机码都转换成小写
			verifyCode = verifyCode.toLowerCase();
			randCode = randCode.toLowerCase();

			if (!verifyCode.equals(randCode)) {
				// 跳转到登录页面，并且共享错误信息
				req.setAttribute("errorMsg", "验证码错误！！！");
				// 请求转发跳转到登录页面
				req.getRequestDispatcher("/login.jsp").forward(req, response);

				return false;
			}

		} else {
			
			if("".equals(verifyCode)) {
				//跳转到登录页面，并且共享错误信息
				req.setAttribute("errorMsg", "验证码不能为空！！！");
				// 请求转发跳转到登录页面
				req.getRequestDispatcher("/login.jsp").forward(req, response);

				return false;
			}
			
		}

		return super.onAccessDenied(request, response);
	}

	/*
	 * 体现Java设计的的包装设计模式 新建一个子类，重写父类方方达，不改变原有父类功能，但是做对应的增强
	 * 
	 */

	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
			ServletResponse response) throws Exception {
		// 在父类的方法执行之前先删除掉Session中共享的上一次请求的 url地址
		WebUtils.getAndClearSavedRequest(request);

		return super.onLoginSuccess(token, subject, request, response);
	}
}
